import { prisma } from '@/config/database';

export const NotesService = {
  // Groups
  async listGroups(userId: string) {
    // 合并“我+伙伴”的分组
    const me = await prisma.user.findUnique({ where: { id: userId }, select: { partnerId: true } });
    const ids = me?.partnerId ? [userId, me.partnerId] : [userId];
    return prisma.noteGroup.findMany({
      where: { userId: { in: ids } },
      orderBy: [{ order: 'asc' }, { createdAt: 'asc' }],
    });
  },
  createGroup(userId: string, name: string) {
    return prisma.noteGroup.create({
      data: { userId, name },
    });
  },
  renameGroup(userId: string, id: string, name: string) {
    return prisma.noteGroup.update({
      where: { id },
      data: { name },
    });
  },
  deleteGroup(userId: string, id: string) {
    // 删除组不删除便签，仅清空 groupId
    return prisma.$transaction([
      prisma.note.updateMany({ where: { userId, groupId: id }, data: { groupId: null } }),
      prisma.noteGroup.delete({ where: { id } }),
    ]);
  },

  // Notes
  async listNotes(userId: string, groupId?: string | null) {
    // 合并“我+伙伴”的可见范围
    const me = await prisma.user.findUnique({ where: { id: userId }, select: { partnerId: true } });
    const ids = me?.partnerId ? [userId, me.partnerId] : [userId];

    const where: any = { userId: { in: ids } };
    if (groupId) {
      // 指定分组仅返回该分组下的便签，前提该分组属于“我或伙伴”
      const group = await prisma.noteGroup.findUnique({ where: { id: groupId }, select: { userId: true } });
      if (!group || !ids.includes(group.userId)) return [];
      where.groupId = groupId;
    }

    return prisma.note.findMany({
      where,
      orderBy: [{ updatedAt: 'desc' }],
      include: { files: true },
    });
  },
  createNote(userId: string, payload: any) {
    const { title, content, groupId, reminderAt } = payload;
    return prisma.note.create({
      data: {
        userId,
        title: title ?? '',
        content: content ?? '',
        groupId: groupId ?? null,
        reminderAt: reminderAt ? new Date(reminderAt) : null,
      },
      include: { files: true },
    });
  },
  updateNote(userId: string, id: string, patch: any) {
    const data: any = {};
    if (patch.title !== undefined) data.title = patch.title;
    if (patch.content !== undefined) data.content = patch.content;
    if (patch.groupId !== undefined) data.groupId = patch.groupId || null;
    if (patch.reminderAt !== undefined) data.reminderAt = patch.reminderAt ? new Date(patch.reminderAt) : null;
    if (patch.timeSpent !== undefined) data.timeSpent = patch.timeSpent;
    return prisma.note.update({
      where: { id },
      data,
      include: { files: true },
    });
  },
  deleteNote(userId: string, id: string) {
    return prisma.$transaction([
      prisma.noteAttachment.deleteMany({ where: { noteId: id } }),
      prisma.note.delete({ where: { id } }),
    ]);
  },

  // Timing
  addTime(userId: string, id: string, seconds: number) {
    return prisma.note.update({
      where: { id },
      data: { timeSpent: { increment: Math.max(0, Math.floor(seconds)) } },
      select: { id: true, timeSpent: true },
    });
  },

  // Attachments
  addAttachment(noteId: string, fileMeta: { kind: string; name: string; mime: string; size: number; url: string }) {
    return prisma.noteAttachment.create({
      data: {
        noteId,
        ...fileMeta,
      },
    });
  },
  listAttachments(noteId: string) {
    return prisma.noteAttachment.findMany({ where: { noteId } });
  },
  removeAttachment(id: string) {
    return prisma.noteAttachment.delete({ where: { id } });
  },
  // 绑定共享模式下不再使用分组共享，保留占位以兼容旧调用（不做任何变更）
  async shareGroup(groupId: string, userIds: string[]) {
    // 去重并合并
    const group = await prisma.noteGroup.findUnique({ where: { id: groupId } });
    const merged = Array.from(new Set([...(group?.sharedWith || []), ...userIds]));
    return prisma.noteGroup.update({
      where: { id: groupId },
      data: { sharedWith: merged },
    });
  },

  async unshareGroup(groupId: string, userId: string) {
    const group = await prisma.noteGroup.findUnique({ where: { id: groupId } });
    const filtered = (group?.sharedWith || []).filter(u => u !== userId);
    return prisma.noteGroup.update({
      where: { id: groupId },
      data: { sharedWith: filtered },
    });
  },

  async getGroupSharedUserIds(groupId: string): Promise<string[]> {
    const g = await prisma.noteGroup.findUnique({ where: { id: groupId }, select: { userId: true, sharedWith: true } });
    if (!g) return [];
    return Array.from(new Set([g.userId, ...(g.sharedWith || [])]));
  }
};